package com.tcdp.services;

import java.util.ArrayList;
import java.util.List;

import com.tcdp.daos.BlogDao;
import com.tcdp.daos.BlogPostCommentDao;
import com.tcdp.delegates.BlogPostCommentDelegate;
import com.tcdp.models.BlogPost;
import com.tcdp.models.BlogPostComment;

public class BlogPostCommentService extends AbstractService {

	public static List<BlogPostCommentDelegate> convertToCommentDelegates(List<BlogPostComment> comments){
		
		List<BlogPostCommentDelegate> commentDelegates = new ArrayList<BlogPostCommentDelegate>();
		
		if(comments == null || comments.size()==0){
			return null;
		}
		
		for(BlogPostComment comment:comments){
			
			BlogPostCommentDelegate commentDelegate = new BlogPostCommentDelegate(comment);
			commentDelegate.setBlogPostCommentChildren(convertToCommentDelegates(comment.getBlogPostCommentChildren()));
			
			commentDelegates.add(commentDelegate);
			
		}
		
		return commentDelegates;
		
	}
	
	public static List<BlogPostComment> convertToCommentObjects(List<BlogPostCommentDelegate> commentDelegates){
		
		List<BlogPostComment> comments = new ArrayList<BlogPostComment>();
		
		if(commentDelegates == null || commentDelegates.size()==0){
			return null;
		}
		
		for(BlogPostCommentDelegate commentDelegate: commentDelegates){
			
			BlogPostComment comment = commentDelegate.getCommentObject();
			comments.add(comment);
			
		}
		
		return comments;
		
	}
	
	public static boolean insertComment(BlogPostCommentDelegate commentDelegate,String blog_post_url,int parent_comment_id){
		return insertComment(commentDelegate.getCommentObject(),blog_post_url,parent_comment_id);
	}
	
	public static boolean insertComment(BlogPostComment comment,String blog_post_url,int parent_comment_id){
		boolean retVal = false;
		
		BlogDao blogDao = new BlogDao();
		BlogPostCommentDao blogPostCommentDao = new BlogPostCommentDao();
		
		BlogPost blog = blogDao.findByUrl(blog_post_url);
		
		if(blog.getBlogPostEnableComments()){
			
			if(parent_comment_id!=-1){			
				BlogPostComment parentComment = blogPostCommentDao.findByKey(parent_comment_id);
				comment.setBlogPostCommentParent(parentComment);
			}
		
			comment.setBlogPost(blog);
			
			retVal = blogPostCommentDao.insertBlogPostComment(comment);
		}
		else{
			System.out.println("WARNING: Cannot post comment on post with commenting disabled.");
		}
		
		return retVal;
	}
}
